package com.tianwen.management.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tianwen.management.entity.LoginUser;
import com.tianwen.management.entity.User;
import com.tianwen.management.entity.UserRolePermission;
import com.tianwen.management.mapper.UserMapper;
import com.tianwen.management.service.PermissionService;
import com.tianwen.management.service.UserRolePermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @program: personnel-management
 * @description
 * @author: tianwen
 * @create: 2023-05-23 14:35
 **/
@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private UserRolePermissionService userRolePermissionService;
    @Resource
    private PermissionService permissionService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        QueryWrapper<User> queryWrapper=new QueryWrapper<>();
        queryWrapper.eq("username",username);
        User user = userMapper.selectOne(queryWrapper);
        if(ObjectUtils.isEmpty(user)){
            throw new RuntimeException("用户名或密码错误");
        }
        QueryWrapper<UserRolePermission> userRolePermissionQueryWrapper=new QueryWrapper<>();
        userRolePermissionQueryWrapper.eq("user_id",user.getId());
        List<UserRolePermission> userRolePermissions = userRolePermissionService.list(userRolePermissionQueryWrapper);

        Set<String> permissionNames=new HashSet<>();
        userRolePermissions.stream().parallel().forEach(userRolePermission -> {
            String name = permissionService.getById(userRolePermission.getPermissionId()).getName();
             permissionNames.add(name);
        });
        List<String> permissions = new ArrayList<>(permissionNames);
        System.err.println(permissions);
        return new LoginUser(user,permissions);
    }
}
